import 'package:flutter/material.dart';
import '../services/auth_service.dart';
import '../main.dart';
import '../widgets/captcha_widget.dart';

class AuthScreen extends StatefulWidget {
  const AuthScreen({super.key});

  @override
  State<AuthScreen> createState() => _AuthScreenState();
}

class _AuthScreenState extends State<AuthScreen> {
  bool _isLogin = true; // 控制显示登录还是注册表单
  final _formKey = GlobalKey<FormState>();
  final _emailController = TextEditingController();
  final _passwordController = TextEditingController();
  final _confirmPasswordController = TextEditingController();
  bool _isPasswordVisible = false;
  bool _isLoading = false;
  final _authService = AuthService();
  final _captchaController = TextEditingController();
  String _currentCaptcha = '';

  @override
  void dispose() {
    _emailController.dispose();
    _passwordController.dispose();
    _confirmPasswordController.dispose();
    _captchaController.dispose();
    super.dispose();
  }

  void _toggleAuthMode() {
    setState(() {
      _isLogin = !_isLogin;
    });
  }

  bool _validateCaptcha() {
    if (_captchaController.text.isEmpty) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text('请输入验证码'),
          backgroundColor: Colors.red,
        ),
      );
      return false;
    }
    if (_captchaController.text.toUpperCase() != _currentCaptcha) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text('验证码错误'),
          backgroundColor: Colors.red,
        ),
      );
      return false;
    }
    return true;
  }

  Future<void> _submit() async {
    if (!_formKey.currentState!.validate()) return;
    if (!_validateCaptcha()) return;

    setState(() {
      _isLoading = true;
    });

    try {
      if (_isLogin) {
        // 实现登录逻辑
        final userData = await _authService.login(
          _emailController.text,
          _passwordController.text,
        );

        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(
              content: Text('欢迎回来，${userData['name']}'),
              backgroundColor: Colors.green,
            ),
          );
          // 登录成功后跳转到主页
          Navigator.of(context).pushReplacement(
            MaterialPageRoute<void>(
              builder: (context) => const ChatScreen(),
            ),
          );
        }
      } else {
        // 实现注册逻辑
        final userData = await _authService.register(
          _emailController.text,
          _passwordController.text,
        );

        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(
              content: Text('注册成功，欢迎 ${userData['name']}'),
              backgroundColor: Colors.green,
            ),
          );
          // 注册成功后跳转到主页
          Navigator.of(context).pushReplacement(
            MaterialPageRoute<void>(
              builder: (context) => const ChatScreen(),
            ),
          );
        }
      }
    } catch (error) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('错误: $error'),
            backgroundColor: Colors.red,
          ),
        );
      }
    }

    if (mounted) {
      setState(() {
        _isLoading = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        decoration: BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topLeft,
            end: Alignment.bottomRight,
            colors: [
              Theme.of(context).primaryColor,
              Theme.of(context).primaryColor.withOpacity(0.8),
            ],
          ),
        ),
        child: SafeArea(
          child: Center(
            child: SingleChildScrollView(
              padding: const EdgeInsets.all(16.0),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  // Logo
                  const Icon(
                    Icons.psychology,
                    size: 100,
                    color: Colors.white,
                  ),
                  const SizedBox(height: 16),
                  // 标题
                  Text(
                    'DeepSeek AI',
                    style: Theme.of(context).textTheme.headlineMedium?.copyWith(
                          color: Colors.white,
                          fontWeight: FontWeight.bold,
                        ),
                  ),
                  const SizedBox(height: 32),
                  // 表单卡片
                  Card(
                    margin: const EdgeInsets.all(20),
                    child: Padding(
                      padding: const EdgeInsets.all(16),
                      child: Form(
                        key: _formKey,
                        child: Column(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            // 标题
                            Text(
                              _isLogin ? '登录' : '注册',
                              style: Theme.of(context).textTheme.titleLarge,
                            ),
                            const SizedBox(height: 16),
                            // 邮箱输入框
                            TextFormField(
                              controller: _emailController,
                              decoration: const InputDecoration(
                                labelText: '邮箱',
                                prefixIcon: Icon(Icons.email),
                                border: OutlineInputBorder(),
                              ),
                              keyboardType: TextInputType.emailAddress,
                              validator: (value) {
                                if (value == null || value.isEmpty) {
                                  return '请输入邮箱';
                                }
                                if (!value.contains('@')) {
                                  return '请输入有效的邮箱地址';
                                }
                                return null;
                              },
                            ),
                            const SizedBox(height: 16),
                            // 密码输入框
                            TextFormField(
                              controller: _passwordController,
                              decoration: InputDecoration(
                                labelText: '密码',
                                prefixIcon: const Icon(Icons.lock),
                                border: const OutlineInputBorder(),
                                suffixIcon: IconButton(
                                  icon: Icon(
                                    _isPasswordVisible
                                        ? Icons.visibility_off
                                        : Icons.visibility,
                                  ),
                                  onPressed: () {
                                    setState(() {
                                      _isPasswordVisible = !_isPasswordVisible;
                                    });
                                  },
                                ),
                              ),
                              obscureText: !_isPasswordVisible,
                              validator: (value) {
                                if (value == null || value.isEmpty) {
                                  return '请输入密码';
                                }
                                if (value.length < 6) {
                                  return '密码长度至少为6位';
                                }
                                return null;
                              },
                            ),
                            const SizedBox(height: 16),
                            // 验证码输入框
                            Row(
                              children: [
                                Expanded(
                                  child: TextFormField(
                                    controller: _captchaController,
                                    decoration: const InputDecoration(
                                      labelText: '验证码',
                                      prefixIcon: Icon(Icons.security),
                                      border: OutlineInputBorder(),
                                    ),
                                    validator: (value) {
                                      if (value == null || value.isEmpty) {
                                        return '请输入验证码';
                                      }
                                      return null;
                                    },
                                  ),
                                ),
                                const SizedBox(width: 16),
                                CaptchaWidget(
                                  onCaptchaGenerated: (captcha) {
                                    _currentCaptcha = captcha;
                                  },
                                  backgroundColor: Colors.white,
                                  textColor: Theme.of(context).primaryColor,
                                ),
                              ],
                            ),
                            const SizedBox(height: 24),
                            // 确认密码输入框（仅注册时显示）
                            if (!_isLogin) ...[
                              TextFormField(
                                controller: _confirmPasswordController,
                                decoration: const InputDecoration(
                                  labelText: '确认密码',
                                  prefixIcon: Icon(Icons.lock),
                                  border: OutlineInputBorder(),
                                ),
                                obscureText: !_isPasswordVisible,
                                validator: (value) {
                                  if (value != _passwordController.text) {
                                    return '两次输入的密码不一致';
                                  }
                                  return null;
                                },
                              ),
                              const SizedBox(height: 16),
                            ],
                            // 提交按钮
                            SizedBox(
                              width: double.infinity,
                              height: 48,
                              child: ElevatedButton(
                                onPressed: _isLoading ? null : _submit,
                                style: ElevatedButton.styleFrom(
                                  backgroundColor:
                                      Theme.of(context).primaryColor,
                                  foregroundColor: Colors.white,
                                ),
                                child: _isLoading
                                    ? const SizedBox(
                                        width: 20,
                                        height: 20,
                                        child: CircularProgressIndicator(
                                          strokeWidth: 2,
                                          valueColor:
                                              AlwaysStoppedAnimation<Color>(
                                                  Colors.white),
                                        ),
                                      )
                                    : Text(_isLogin ? '登录' : '注册'),
                              ),
                            ),
                            const SizedBox(height: 16),
                            // 切换登录/注册按钮
                            TextButton(
                              onPressed: _toggleAuthMode,
                              child: Text(
                                _isLogin ? '没有账号？点击注册' : '已有账号？点击登录',
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }
}
